package com.learn.security.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密基础
 */
public class BaseUtil {
    /**
     * BASE64解密
     *
     * @param key 解密字符串
     */
    public static byte[] decryptBASE64(String key) {
        try {
            return (new BASE64Decoder()).decodeBuffer(key);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * BASE64加密
     *
     * @param key 加密的字符串
     */
    public static String encryptBASE64(byte[] key) {
        return (new BASE64Encoder()).encodeBuffer(key);
    }

    /**
     * SHA和MD加密
     *
     * @param data      加密文件
     * @param algorithm the name of the algorithm requested.
     */
    protected static byte[] encryptSHAAndMd(byte[] data, String algorithm) {
        try {
            MessageDigest sha = MessageDigest.getInstance(algorithm);
            sha.update(data);
            return sha.digest();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
}
